#include <stdio.h>
#include <string>

#include "Communicator.h"
#include "BasicTypes.h"
#include "InputMessage.h"
#include "OutputMessage.h"
#include <windows.h>

using namespace std;

Communicator::Communicator()
{
}

Communicator::~Communicator()
{
}

pInputMessage Communicator::ReadMessage()
{
	unsigned int header = 0;
	DWORD read;
	ReadFile(GetStdHandle(STD_INPUT_HANDLE), &header, 4, &read, NULL);
	if (read == 0)
		return IInputMessage::Create( MT_SHUTDOWN, "" );
	else
	{
		streamsize size = header / 256;
		MessageType type = (MessageType)(header % 256);
		string msg;
		if (size > 0)
		{
			char * message = new char[size];
			ReadFile(GetStdHandle(STD_INPUT_HANDLE), message, size, &read, NULL);
			msg = string( message, size );
			delete message;
		} else {
			msg = "";
		}
		return IInputMessage::Create( type, msg );
	}
}

void Communicator::WriteMessage(const IOutputMessage & message)
{
	DWORD written;
	WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), message.Message().c_str(), (DWORD)message.Message().length(), &written, NULL);
}